package com.lier.gulimall.auth.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.client.naming.net.HttpClient;
import com.lier.common.constant.AuthServerConstant;
import com.lier.common.utils.R;
import com.lier.common.vo.GiteeTokenVo;
import com.lier.common.vo.MemberResponseVo;
import com.lier.gulimall.auth.feign.MemberFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liyd
 * @description
 * @date 2025/8/25 11:43
 */
@Controller
public class Oauth2CallbackController {

    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) {

        Map<String,String> paramValues = new HashMap<>();
        paramValues.put("grant_type", "authorization_code");
        paramValues.put("code", code);
        paramValues.put("client_id", "5322b06ee081fb00674c4dfd897d2d7650b462445c09b18d60a1f5afd4b5d3ea");
        paramValues.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/gitee/success");
        paramValues.put("client_secret", "600c9a2d85fa492d16253a306e46a86ed0c0cb263d7ddc8e8fc4caefaa4e8bb8");

        HttpClient.HttpResult result= HttpClient
                .request("https://gitee.com/oauth/token", null,
                        paramValues, "UTF-8", "POST");

        if(result.code == 200){
            String json = result.content;
            GiteeTokenVo giteeTokenVo = JSONObject.parseObject(json, GiteeTokenVo.class);

            R r = memberFeignService.giteeLogin(giteeTokenVo);

            if(r.getCode() == 0){
                MemberResponseVo loginUser = r.getData(new TypeReference<MemberResponseVo>(){});
                session.setAttribute(AuthServerConstant.LOGIN_USER, loginUser);
                return "redirect:http://gulimall.com";
            }else {
                // 登录失败，调回登录页
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
